<?php

namespace common\entities\myhtsq;

use common\entities\ContractEntity;
use common\repositories\common\MyscrmContractRepository;
use common\repositories\myhtsq\ContractManageRepository;
use common\repositories\myhtsq\ContractRevenueRepository;
use common\repositories\myhtsq\RevenueRecognitionRepository;
use Yii;

/**
 * This is the model class for table "myscrm_contract_revenue".
 *
 * @property string $revenue_id
 * @property string $contract_id
 * @property string $revenue_type
 * @property string $amount
 * @property string $created_on
 * @property string $created_by
 * @property string $modified_on
 * @property string $modified_by
 * @property int $close_status
 * @property string $income_code
 * @property string $establish_time
 * @property string $begin_on
 * @property string $end_on
 * @property decimal $unrecognized_bad_debt_amount
 * @property decimal $recognized_bad_debt_amount
 * @property decimal $kingdee_bad_debt_amount
 * @property string $maintain_remark
 * @property int $add_type
 * @property string $parent_id
 */
class ContractRevenueEntity extends ContractEntity
{
	public $type_name;
    public $erp_contract_id;
    public $erp_contract_code;

    /**
     * 关闭状态
     */
    const CLOSE_STATUS_NOT = 1; //未关闭
    const CLOSE_STATUS_HAND = 2;   //手动关闭
    const CLOSE_STATUS_AUTO = 3;   //自动关闭
    const CLOSE_STATUS_CONFIRMED = 4;   //已结转


    /**
     * 收入项操作动作
     */
    const OPERATE_ADD = 'add';
    const OPERATE_EDIT = 'edit';

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'myscrm_contract_revenue';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['revenue_id'], 'required'],
            [['amount','unrecognized_bad_debt_amount','recognized_bad_debt_amount','kingdee_bad_debt_amount','close_status','add_type'], 'number'],
            [['establish_time','created_on', 'modified_on'],'string','max' => 36],
            [['revenue_id', 'contract_id', 'created_by','revenue_type', 'modified_by','erp_contract_id','erp_contract_code','parent_id'], 'string', 'max' => 36],
            ['maintain_remark','string','max'=>255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'revenue_id' => '收入ID',
            'contract_id' => '合同ID',
            'revenue_type' => '收入类型',
            'amount' => '金额',
            'created_on' => '创建时间',
            'created_by' => '创建人',
            'modified_on' => '修改时间',
            'modified_by' => '修改人',
        ];
    }
    
    /**
     * 根据合同id,获取收入信息
     * @param string $contractId 合同id
     * @return array
     */
    public static function getContractRevenueListByContractId($contractId) {
    	return self::find()->where(['contract_id'=>$contractId])->all();
    }
    
    /**
     * 根据收入id 删除收入信息
     * @param string $revenueId
     * @return boolean
     */
    public static function deleteContractRevenueByRevenueId($revenueId) {
    	return self::deleteAll(['revenue_id'=>$revenueId]);
    }

    /**
     * 收入项生成检查
     * @param $action
     * @param $contract_type
     * @return bool
     * @throws \Exception
     */
    public function generateCheck($action,$contract_type){
        if($this->contract_id){
            if($contract_type == 'yk'){
                $contract_balance_amount = ContractManageRepository::getSignAmount($this->contract_id);//已生成的收入项金额
            }else{
                $contract_balance_amount = MyscrmContractRepository::getApplicationPayOverAmountSum($this->contract_id);//合同收入项金额
            }
            $contract_income_amount = ContractRevenueRepository::getContractRevenueSumByContractId($this->contract_id);//已生成的收入项金额
            if($action == self::OPERATE_ADD){
                if($this->parent_id){
                    $parent_total_amount = ContractRevenueRepository::getParentRevenueSum($this->parent_id);
                    $sum_red_flush = ContractRevenueRepository::getRevenueRedFlushSum($this->parent_id);
                    if(round($parent_total_amount + $this->amount + $sum_red_flush,2) < 0){
                        throw new \Exception('此次对冲金额【'.$this->amount .'】+已对冲金额【'.$sum_red_flush.'】的绝对值不应大于父收入项的金额【'.sprintf("%2d",$parent_total_amount).'】');
                    }else{
                        return true;
                    }
                }
                if(round($contract_balance_amount - $contract_income_amount,2) >= round($this->amount,2)){
                    return true;
                }
                throw new \Exception('待生成的收入项不满足生成条件 ：合同总的结算金额【'.$contract_balance_amount .'】-已生成的收入项金额【'.$contract_income_amount.'】不应小于本次新增的金额【'.$this->amount.'】');
            }elseif($action == self::OPERATE_EDIT){
                if($this->close_status == self::CLOSE_STATUS_HAND || $this->close_status == self::CLOSE_STATUS_HAND){
                    $check = $this->closeCheck();
                    if(!$check){
                        throw new \Exception('此收入项不满足关闭条件');
                    }
                    return $check;
                }
                $old_revenue_type = $this->getOldAttribute('revenue_type');
                $old_begin_on = $this->getOldAttribute('begin_on');
                $old_end_on = $this->getOldAttribute('end_on');
                $old_establish_time = $this->getOldAttribute('establish_time');
                $old_revenue_amount = $this->getOldAttribute('amount');


                $recognition = RevenueRecognitionRepository::getRevenueRecognitionListByRevenueId($this->revenue_id);
                if(!empty($recognition)) {
                    //判断已结转收入项的关键信息是否有变动,
                    if($old_revenue_amount == $this->amount && $old_revenue_type == $this->revenue_type && $old_begin_on == $this->begin_on && $old_end_on == $this->end_on &&  $old_establish_time == $this->establish_time){
                        return true;
                    }else{
                        return round($contract_balance_amount - $contract_income_amount,2);
                    }
                    throw new \Exception('此收入项已经生成结转,对'.$this->income_code.'收入项的修改已跳过');
                }

                // TODO 算上红冲
                $sum_red_flush = ContractRevenueRepository::getRevenueRedFlushSum($this->revenue_id);
                if( round($this->amount-($old_revenue_amount+$sum_red_flush),2) != 0){
                    return round($this->amount-($old_revenue_amount+$sum_red_flush),2);
                }

                if(round($contract_balance_amount-($contract_income_amount- ($old_revenue_amount+$sum_red_flush)),2) >= round($this->amount,2)){
                    return true;
                }

                throw new \Exception('待生成收入项【'.$this->amount.'】+' . '已生成收入项【'.($contract_income_amount- $old_revenue_amount).'】不应大于合同总的结算金额【'.$contract_balance_amount.'】');
            }
        }
        return true;
    }


    /**
     * 关闭收入项检查
     */
    public function closeCheck(){
        if($this->revenue_id && ($this->close_status == self::CLOSE_STATUS_AUTO || $this->close_status == self::CLOSE_STATUS_HAND)){
            $revenue_amount = $this->amount;//当前收入项需转结的金额
            $totalConfirmedAmount = RevenueRecognitionRepository::getTotalConfirmedAmount($this->revenue_id);//当前收入项所属的总的已确认金额
            $latestCarryOver = RevenueRecognitionRepository::getLatestCarryoverByRevenueId($this->revenue_id);//最近一次转结
            $unConfirmedAmount = round($revenue_amount - $totalConfirmedAmount,2);
            $condition_1 = ($unConfirmedAmount == 0 || round($unConfirmedAmount - intval($this->unrecognized_bad_debt_amount),2) == 0)?true:false;
            $condition_2 = (round($revenue_amount,2) == round($totalConfirmedAmount + $unConfirmedAmount + $this->unrecognized_bad_debt_amount,2))?true:false;
            $condition_3 = (round($latestCarryOver->this_period_confirm_total_amount,2) == round($latestCarryOver->recognition_amount + $latestCarryOver->last_period_total_confirm_amount,2))?true:false;
            if($condition_1 === false){
                Yii::info(var_export('$totalConfirmedAmount=>'.$totalConfirmedAmount,true),'carry_over_log');
                Yii::info(var_export('$unConfirmedAmount=>'.$unConfirmedAmount,true),'carry_over_log');
                Yii::info('收入项关闭检查'.$this->revenue_id.'条件1不满足:(待确认收入)'.$unConfirmedAmount .'= 0 或者 (未确认已发生坏账)'.intval($this->unrecognized_bad_debt_amount) .'-(待确认金额)'.$unConfirmedAmount,'carry_over_log');
            }
            if($condition_2 === false){
                Yii::info('收入项关闭检查'.$this->revenue_id.'条件2不满足:(收入项金额)'.$revenue_amount .'==(当期累计确认收入)'.$totalConfirmedAmount.'+(待确认金额)'.$unConfirmedAmount.'+(未确认收入已发生坏账)'.$this->unrecognized_bad_debt_amount,'carry_over_log');
            }
            if($condition_3 === false){
                Yii::info('收入项关闭检查'.$this->revenue_id.'条件3不满足:(当期累计确认收入)'.$latestCarryOver->this_period_confirm_total_amount.'=(上期累计确认收入)'.$latestCarryOver->last_period_total_confirm_amount.'+(当期确认收入)'.$latestCarryOver->recognition_amount .'(结果)'.($latestCarryOver->recognition_amount + $latestCarryOver->last_period_total_confirm_amount),'carry_over_log');
            }
            if($condition_1 && $condition_2 && $condition_3){
                return true;
            }
            return false;
        }
        return true;
    }


    /**
     * 转结检查
     * @param $carry_over_data
     * @return bool
     */
    public function carryOverCheck($carry_over_data){
        if($this->revenue_id){
            $revenue_amount = $this->amount;//当前收入项需转结的金额
            $totalConfirmedAmount = RevenueRecognitionRepository::getTotalConfirmedAmount($this->revenue_id);//当前收入项所属的总的已确认金额
            $latestCarryOver = RevenueRecognitionRepository::getLatestCarryoverByRevenueId($this->revenue_id);//所有的转结
            $unConfirmedAmount = round($revenue_amount - $totalConfirmedAmount,2);

            //转结一次以上才会校验    上期的当期累计确认收入=当期的上期累计收入
            if(empty($latestCarryOver)){
                $condition_1 = true;
            }else{
                $condition_1 = ($latestCarryOver->this_period_confirm_total_amount == $carry_over_data['last_period_total_confirm_amount'])?true:false;
            }
            $condition_2 = (round($revenue_amount,2) == round($totalConfirmedAmount + $unConfirmedAmount + $this->unrecognized_bad_debt_amount,2))?true:false;
            $condition_3 = (round($carry_over_data['this_period_confirm_total_amount'],2) == round($carry_over_data['last_period_total_confirm_amount']+$carry_over_data['recognition_amount'],2))?true:false;
            if($condition_1 === false){
                Yii::info('收入项转结检查'.$this->revenue_id.'条件1不满足:(上期的当期累计确认收入)'.$latestCarryOver->this_period_confirm_total_amount .'=(当期的上期累计确认收入)'.$carry_over_data['this_period_confirm_total_amount'],'carry_over_log');
            }
            if($condition_2 === false){
                Yii::info('收入项转结检查'.$this->revenue_id.'条件2不满足:(收入项金额)'.$revenue_amount .'==(当期累计确认收入)'.$totalConfirmedAmount.'+(待确认金额)'.$unConfirmedAmount.'+(未确认收入已发生坏账)'.$this->unrecognized_bad_debt_amount,'carry_over_log');
            }
            if($condition_3 === false){
                Yii::info('收入项转结检查'.$this->revenue_id.'条件3不满足:(当期累计确认收入)'.round($carry_over_data['this_period_confirm_total_amount'],2).'=(上期累计确认收入)'.round($carry_over_data['last_period_total_confirm_amount'],2).'+(当期确认收入)'.round($carry_over_data['recognition_amount'],2),'carry_over_log');
            }
            if($condition_1 && $condition_2 && $condition_3){
                return true;
            }
            return false;
        }
        return true;
    }
}
